/*
 *  Copyright 2020-2025 the original author or authors.
 *  You cannot use this file unless authorized by the author.
 */

package org.ipig.search.es;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.ipig.search.es.parm.SearchParm;
import org.ipig.search.es.result.SearchResult;

/**
 * 检索管理
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id$$
 * @since 1.0
 */
@Slf4j
public class SearchManager {
    /**
     * Missing聚合【missing】
     */
    public static final String AGGS_MISSING = "aggsMissing";
    /**
     * 日期区间聚合【dateRange】
     */
    public static final String AGGS_DATE_RANGE = "aggsDateRange";
    /**
     * 区间聚合【Range】
     */
    public static final String AGGS_RANGE = "aggsRange";
    /**
     * 多过滤器聚合【filters】
     */
    public static final String AGGS_FILTERS = "aggsfilters";
    /**
     * 过滤器聚合【filter】
     */
    public static final String AGGS_FILTER = "aggsfilter";
    /**
     * 分组聚合【terms】
     */
    public static final String AGGS_TERMS = "aggsTerms";
    /**
     * count文档数量统计
     */
    public static final String AGGS_VALUE_COUNT = "aggsValueCount";
    /**
     * percentiles百分位统计
     */
    public static final String AGGS_PERCENTILES = "aggsPercentiles";
    /**
     * cardinality基数统计
     */
    public static final String AGGS_CARDINALITY = "aggsCardinality";
    /**
     * extendedStats高级统计
     */
    public static final String AGGS_EXTENDED_STATS = "aggsExtendedStats";
    /**
     * stats基本统计
     */
    public static final String AGGS_STATS = "aggsStats";
    /**
     * avg平均值统计
     */
    public static final String AGGS_AVG = "aggsAvg";
    /**
     * sum合计统计
     */
    public static final String AGGS_SUM = "aggsSum";
    /**
     * min最小值统计
     */
    public static final String AGGS_MIN = "aggsMin";
    /**
     * max最大值统计
     */
    public static final String AGGS_MAX = "aggsMax";

    /**
     * 匹配查询
     *
     * @param client     Client
     * @param searchParm SearchParm
     * @return SearchResult
     */
    public static SearchResult matchQuery(Client client, SearchParm searchParm) {
        SearchResult result = new SearchResult();
        AggregationBuilder aggs = searchParm.getAggsBuilder();
        QueryBuilder query = searchParm.getQueryBuilder();
        SortBuilder<?> sort = searchParm.getSortBuilder();
        SearchRequestBuilder search = client.prepareSearch(searchParm.getIndexName());
        if (query != null) {
            search.setQuery(query);
        }
        if (aggs != null) {
            search.addAggregation(aggs);
        }
        if (sort != null) {
            search.addSort(sort);
        }
        search.setSize(searchParm.getSize()).setFrom(searchParm.getFrom());
        log.debug(search.toString());
        SearchResponse response = search.get();
        log.debug(response.toString());
        result.setSearchHits(response.getHits());
        result.setAggs(response.getAggregations());
        result.setShardFailuresArray(response.getShardFailures());
        result.setSuggest(response.getSuggest());
        result.setShardProfileMap(response.getProfileResults());
        return result;
    }

    /**
     * 全查询
     *
     * @param client    Client
     * @param indexName 索引名
     * @param size      大小
     * @param from      开始值
     * @return SearchResult
     */
    public static SearchResult allQuery(Client client, String indexName, int size, int from) {
        QueryBuilder query = QueryBuilders.matchAllQuery();
        SearchParm map = new SearchParm();
        map.setFrom(from);
        map.setSize(size);
        map.setQueryBuilder(query);
        return matchQuery(client, map);
    }

}